#include "vehgui.h"
#include "portable-file-dialogs.h"


VehGUI::VehGUI(osg::Group* pNode, osgViewer::Viewer* pView) :
    ImGuiPanel("Vehicle"), node(pNode), view(pView)
{

}


bool VehGUI::insertVeh(const std::string& fName)
{
    std::shared_ptr<EquipNode>  veh = std::make_shared<EquipNode>(fName);
    if (veh->IsLoaded())
    {
        if (vehs.find(veh->name()) != vehs.end())
            return false;

        veh->setRotoate(osg::Vec3(-osg::PI_2,0,0));
        veh->setPosition(osg::Vec3(13, 120, 0));
        veh->setColor(osg::Vec4(1, 1, 1, 0.2));
        node->addChild(veh->get());

        {
            std::lock_guard<std::mutex> lock(map_lock);
            vehs.insert_or_assign(veh->name(), veh);
        }

        return true;
    }
    return false;
}


void VehGUI::draw(osg::RenderInfo& ri)
{
    if (!isVisible())  return;

    ImGui::Begin(name(), visible());

    for(iter = vehs.begin(); iter != vehs.end(); ++iter)
    {
        auto veh = iter->second;
        int i = 1;
        if (ImGui::TreeNode(veh->name().c_str()))
        {
            float  p[3];
            veh->pos(p);
            if (ImGui::DragFloat2("Position", p, 0.1f, 0.0f, 360.0f, "%.1f"))
            {
                veh->setPosition(osg::Vec3(p[0], p[1], p[2]));
            }
            veh->rot(p);
            if (ImGui::DragFloat3("Rotate", p, 5, 0.0f, 360.0f, "%.1f"))
            {
                veh->setRotoate(osg::Vec3(p[0]*osg::PI/180.0f, p[1]*osg::PI/180.0f, p[2]*osg::PI/180.0f));
            }
            veh->clr(p);
            if (ImGui::ColorEdit3("Color", p))
            {
                veh->setColor(osg::Vec4(p[0], p[1], p[2], veh->capacity()));
            }
            float f = veh->capacity();
            if (ImGui::SliderFloat("Capacity", &f, 0.0, 1.0f, "%.1f"))
            {
                veh->setColor(osg::Vec4(p[0], p[1], p[2], f));
            }

            if ( ImGui::Button("Goto") )
            {
                oeUtils::FlyToPosition(node, view, veh->pos());
            }
            ImGui::TreePop();
        }
    }


    if (ImGui::Button("Add"))
    {
        auto f = pfd::open_file("Chose model fiel to load", "/home/cm/Develop/03-VC/osgData/Models/", {"Object file", "*.obj"}, pfd::opt::none);
        if (f.result().size() > 0)
        {
            std::string fName = f.result()[0];
            insertVeh(fName);
        }
    }
    ImGui::End();
}
